/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011      Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
 
http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lua;

import java.util.HashMap;
import java.util.Map;

import org.cocos2dx.exten.SGAppUtils;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxHelper;
import org.cocos2dx.plugin.PluginWrapper;
import org.json.JSONObject;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.soulgame.sgand.SGAndResult;
import com.soulgame.sgand.SGAndSdk;
import com.soulgame.sgand.constant.PayInfoKey;
import com.soulgame.sgand.constant.SGAndConstant;
import com.soulgame.sgand.proxy.SdkCallBack;
import com.soulgame.sgand.proxy.SdkListener;
import com.umeng.mobclickcpp.MobClickCppHelper;

public class AppActivity extends Cocos2dxActivity
{
	private SGAppUtils sgAppUtils;
	private static String hostIPAdress;
	private static Handler handler;
    
    static {
        MobClickCppHelper.loadLibrary();
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        initHandler();
 		MobClickCppHelper.init(this);
 		sgAppUtils = new SGAppUtils();
        sgAppUtils.init(this);
 		PluginWrapper.init(this);
 		
 		initPay();
	}
    
	private void initPay() {
		if (SGAppUtils.getTest()) {
			SGAppUtils.setConfig(false, false, false, false, false, 3);
			return;
		}

		SGAndSdk.initSdk(AppActivity.this, false, new SdkListener() {
			@Override
			public void onLoginResult(Map<String, String> pUserInfos) {
				AppActivity.this.runOnGLThread(new Runnable() {
					@Override
					public void run() {
						SGAppUtils.commandToLua("login", "true");
					}
				});
			}
			@Override
			public void onNotifyBundle(Bundle bd) {
				Log.e("AppActivity", bd.toString());

				try{
					String bdStr = bd.getString("control");						
					JSONObject obj = new JSONObject(bdStr);
				
					Boolean propsCtrl = obj.getBoolean("nGamePop");
					Boolean failCtrl = obj.getBoolean("nFailPop");
					Boolean startCtrl = obj.getBoolean("nStartPop");
					Boolean powerCtrl = obj.getBoolean("nEnergyPop");
					Boolean clewCtrl = obj.getBoolean("nWord");
					int buttonCtrl = obj.getInt("nButton");
					SGAppUtils.setConfig(propsCtrl, failCtrl, startCtrl, powerCtrl, clewCtrl, buttonCtrl);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			@Override
			public void onCallBack(int errorCode, final String message) {
				if( errorCode == SGAndResult.PAYRESULT_SUCCESS ){
					Log.e("=======sucBack", "pid " + message);
					AppActivity.this.runOnGLThread(new Runnable() {
						@Override
						public void run() {
							final String fgoods = message;
							SGAppUtils.payForProductResult(0, fgoods);
						}
					});
				}else if( errorCode == SGAndResult.PAYRESULT_FAIL ){
					Log.e("=======failBack", "arg1 " + message);
					AppActivity.this.runOnGLThread(new Runnable() {
						@Override
						public void run() {
							final String fgoods = message;
							SGAppUtils.payForProductResult(-1, fgoods);
						}
					});
				}else if( errorCode == SGAndResult.PAYRESULT_CANCEL ){
					Log.e("=======cancelBack", "arg1 " + message);
					AppActivity.this.runOnGLThread(new Runnable() {
						@Override
						public void run() {
							final String fgoods = message;
							SGAppUtils.payForProductResult(-1, fgoods);
						}
					});
				}
			}				
		});//luoyuanchao
		
	}
	
	/**
	 * 释放
	 */
	public void realse() {
	//	if (mPushAgent.isEnabled()) {
	//		mPushAgent.disable();
	//	}
	}

	public static enum MsgType{
		initPay,		// 3000
		soulpay,		// 10000
		showToast, 		// 0
		exitGame,  		// 0x14
		dialNumber, 	// 119
		getLocation, 	// 222
		gamePause,
		gameResume,
		login360, 
		showInterstitial,
	}
	
	public static void handleMessage(MsgType msgType, Object obj) {
		Message msg = new Message();
		msg.what = msgType.ordinal();
		msg.obj = obj;
		AppActivity.handleMessage(msg);
	}
     
    public String getHostIpAddress() {
        WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
        int ip = wifiInfo.getIpAddress();
        return ((ip & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF));
    }
    
    public static String getLocalIpAddress() {
        return hostIPAdress;
    }
    
    private static native boolean nativeIsLandScape();
    private static native boolean nativeIsDebug();
	
	private void initHandler() {

		handler = new Handler(){
 			public void handleMessage(Message msg) {
 				MsgType msgtype = MsgType.values()[msg.what];
 				switch (msgtype) {
 				case showToast:
 					show((String)msg.obj);
 					break;
 				case exitGame:
// 					SoulPay.exitGame(AppActivity.this);
// 					SGSDKDelegate.getInstance().exit();
// 					SGAndSdk.exit(AppActivity.this);//luoyuanchao
 					exitGame();
 					break;
 				case dialNumber:
 					dialNumber((String)msg.obj);
 					break;
 				case getLocation:
 					SGAppUtils.getLocation();
 					break;
 				case initPay:
// 					initPay();//luoyuanchao:如果要将百度闪屏放在游戏前面，就要把这个初始化放在onCreate里
 					break;
 				case soulpay:
 					soulpay((String)msg.obj);
 					break;
 				case gamePause:
// 					SoulPay.pauseGame(AppActivity.this);
// 					SGSDKDelegate.getInstance().pauseGame();
 					SGAndSdk.pauseGame(AppActivity.this);//luoyuanchao
 					break;
				case login360:
//					doSdkLogin(false);
					SGAndSdk.doSdkLogin();
					break;
				case showInterstitial:
					showInterstitial();
 				default:
 					break;
 				}
 			}

			private void show(String obj) {
				// TODO Auto-generated method stub
				Toast.makeText(AppActivity.this, obj, Toast.LENGTH_SHORT).show();
			}
			
			private void dialNumber(final String number) {
				Log.e("soulgame", "number "+number);
				Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+number)); 
			    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			    startActivity(intent);
			}
			
			private void initPay() {
				if (SGAppUtils.getTest()) {
					SGAppUtils.setConfig(false, false, false, false, false, 3);
					return;
				}
//				SGAppUtils.setConfig(true, true, true, true, true, 3);//luoyuanchao官方包

				//支付SDK
//				SoulPay.init(AppActivity.this, new IPayCallback() {
//					@Override
//					public void cancelBack(final String arg0) {
//						// TODO Auto-generated method stub
//						Log.e("=======cancelBack", "pid " + arg0);
//						AppActivity.this.runOnGLThread(new Runnable() {
//							@Override
//							public void run() {
//								final String fgoods = arg0;
//								SGAppUtils.payForProductResult(-1, fgoods);
//							}
//						});
//					}
//					@Override
//					public void failBack(final String arg0) {
//						// TODO Auto-generated method stub
//						Log.e("=======failBack", "arg1 " + arg0);
//						AppActivity.this.runOnGLThread(new Runnable() {
//							@Override
//							public void run() {
//								final String fgoods = arg0;
//								SGAppUtils.payForProductResult(-1, fgoods);
//							}
//						});
//					}
//					@Override
//					public void sucBack(final String arg0) {
//						// TODO Auto-generated method stub
//						Log.e("=======sucBack", "pid " + arg0);
//						AppActivity.this.runOnGLThread(new Runnable() {
//							@Override
//							public void run() {
//								final String fgoods = arg0;
//								SGAppUtils.payForProductResult(0, fgoods);
//							}
//						});
//					}
//					@Override
//					public void notifyBundle(final Bundle bd) {
//						// TODO Auto-generated method stub
//						Log.e("AppActivity", bd.toString());
//						Boolean propsCtrl = bd.getBoolean("propsCtrl");
//						Boolean failCtrl = bd.getBoolean("failCtrl");
//						Boolean startCtrl = bd.getBoolean("startCtrl");
//						Boolean powerCtrl = bd.getBoolean("powerCtrl");
//						Boolean clewCtrl = bd.getBoolean("clewCtrl");
//						int buttonCtrl = bd.getInt("buttonCtrl");
//						SGAppUtils.setConfig(propsCtrl, failCtrl, startCtrl, powerCtrl, clewCtrl, buttonCtrl);
//					}
//				});

				SGAndSdk.initSdk(AppActivity.this, false, new SdkListener() {
					@Override
					public void onLoginResult(Map<String, String> pUserInfos) {
						AppActivity.this.runOnGLThread(new Runnable() {
							@Override
							public void run() {
								SGAppUtils.commandToLua("login", "true");
							}
						});
					}
					@Override
					public void onNotifyBundle(Bundle bd) {
						Log.e("AppActivity", bd.toString());

						try{
							String bdStr = bd.getString("control");						
							JSONObject obj = new JSONObject(bdStr);
						
							Boolean propsCtrl = obj.getBoolean("nGamePop");
							Boolean failCtrl = obj.getBoolean("nFailPop");
							Boolean startCtrl = obj.getBoolean("nStartPop");
							Boolean powerCtrl = obj.getBoolean("nEnergyPop");
							Boolean clewCtrl = obj.getBoolean("nWord");
							int buttonCtrl = obj.getInt("nButton");
							SGAppUtils.setConfig(propsCtrl, failCtrl, startCtrl, powerCtrl, clewCtrl, buttonCtrl);
						}catch(Exception e){
							e.printStackTrace();
						}
					}
					@Override
					public void onCallBack(int errorCode, final String message) {
						if( errorCode == SGAndResult.PAYRESULT_SUCCESS ){
							Log.e("=======sucBack", "pid " + message);
							AppActivity.this.runOnGLThread(new Runnable() {
								@Override
								public void run() {
									final String fgoods = message;
									SGAppUtils.payForProductResult(0, fgoods);
								}
							});
						}else if( errorCode == SGAndResult.PAYRESULT_FAIL ){
							Log.e("=======failBack", "arg1 " + message);
							AppActivity.this.runOnGLThread(new Runnable() {
								@Override
								public void run() {
									final String fgoods = message;
									SGAppUtils.payForProductResult(-1, fgoods);
								}
							});
						}else if( errorCode == SGAndResult.PAYRESULT_CANCEL ){
							Log.e("=======cancelBack", "arg1 " + message);
							AppActivity.this.runOnGLThread(new Runnable() {
								@Override
								public void run() {
									final String fgoods = message;
									SGAppUtils.payForProductResult(-1, fgoods);
								}
							});
						}
					}				
				});//luoyuanchao
				
			}
			
			private void soulpay(final String pid) {
				if (SGAppUtils.getTest()) {
					return;
				}
/*				
				AppActivity.this.runOnGLThread(new Runnable() {
					@Override
					public void run() {
						final String fgoods = pid;
						SGAppUtils.payForProductResult(0, fgoods);
					}
				});//白包
*/

				Log.e("AppActivity", "product:"+pid);
//				SoulPay.pay(product);
//				SGSDKDelegate.getInstance().doPay(product);				
				int goodprice = sgAppUtils.getGoodPriceByPid(pid);
				String productName = sgAppUtils.getProductNameByGoodId(pid);
				HashMap<String, String> customPace = new HashMap<String, String>();
				customPace.put(PayInfoKey.PRODUCT_ID, pid);
				int pidend = Integer.valueOf(pid.split("_")[1]);
				if(pidend > 20){
					customPace.put(PayInfoKey.PAY_FUNCTION_CODE, SGAndConstant.PAY_FUN_TWO);
				}
				SGAndSdk.doPay(AppActivity.this, pid, productName, goodprice, customPace);//luoyuanchao

			}
			
 		};
	}
	
	public static void setMusicEnabled(boolean isMusic) {
		Cocos2dxHelper.setIntegerForKey("music", isMusic?1:0);
		Cocos2dxHelper.setIntegerForKey("sound", isMusic?1:0);
	}
	
	public static void handleMessage(Message msg) {
		handler.sendMessage(msg);
	}
	
	// 播放插屏广告
	public void showInterstitial(){
	}

	@Override
	public void onResume() {
	    super.onResume();
	 //   UMGameAgent.onResume(this);
//	    SoulPay.onResume(this);
//	    SGSDKDelegate.getInstance().onResume();
	    SGAndSdk.onResume();//luoyuanchao
	}
	  
	@Override
	public void onPause() {
	    super.onPause();
	 //   UMGameAgent.onPause(this);
//	    SoulPay.onPause(this);
//	    SGSDKDelegate.getInstance().onPause();
	    SGAndSdk.onPause();//luoyuanchao
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
//		SoulPay.onDestroy(this);
//		SGSDKDelegate.getInstance().onDestroy();
		SGAndSdk.onDestroy();//luoyuanchao
//		System.exit(0);
		
		Cocos2dxHelper.pauseBackgroundMusic();
        android.os.Process.killProcess(android.os.Process.myPid());
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
	
	public void exitGame() {
//		SoulPay.exitGame(this);
//		SGSDKDelegate.getInstance().exit();
//		SGAndSdk.exit(this);//luoyuanchao
		
        SGAndSdk.exit(AppActivity.this, new SdkCallBack(){
            @Override
            public void onCallBack(int resultCode, String message) {
                if(0==resultCode){
                	AppActivity.this.finish();                  
                }               
            }           
        });
	}
   
}
